package persistenciatest;

import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

public class SessionManager {
	private static SessionManager uniqueInstance = new SessionManager();
	private SessionFactory sessionFactory;
	private ThreadLocal<Session> sessions = new ThreadLocal<Session>();
	
	public SessionManager() {
		Configuration cfg = new Configuration();
		cfg.configure();
		sessionFactory = cfg.buildSessionFactory();
	}
	
	public static SessionManager getInstance(){
		return uniqueInstance;
	}

	public void runInSession(Runnable closure) {
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		sessions.set(session);
		
		try{
			closure.run();
			session.flush();
			transaction.commit();
		}catch(RuntimeException e){
			transaction.rollback();
			throw e;
		}finally{
			session.close();
			sessions.set(null);
		}
	}

	public Session getSession() {
		return sessions.get();
	}

	public static void clear() {
		uniqueInstance.sessionFactory.close();
		uniqueInstance = new SessionManager();
	}
}
